<template>
  <div class="index" v-if="isChange">
    <div class="upload-menu">
      <input type="file" class="upload" @change="doUpload" ref="inputer" multiple id="default-btn"/>
      <el-button type="primary" @click="startAll" :disabled="tableData.length < 1">全部开始</el-button>
      <el-button type="warning" @click="pauseAll" :disabled="tableData.length < 1">全部暂停</el-button>
      <el-button type="danger" @click="clearAll" :disabled="tableData.length < 1">全部删除</el-button>
    </div>

    <div class="upload-content">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="180">
        </el-table-column>
        <el-table-column prop="fileName" label="文件名" width="180">
        </el-table-column>
        <el-table-column prop="size" label="文件大小" width="180">
          <template #default="scope">{{ transformSize(scope.row.size)}}</template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="180">
          <template #default="scope">
            <el-progress :text-inside="true" :stroke-width="26" :percentage="scope.row.progress"></el-progress>
          </template>

        </el-table-column>
        <el-table-column prop="progress" label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="start(scope.row.id)">开始</el-button>
            <el-button type="warning" size="small" @click="stop(scope.row.id)">暂停</el-button>
            <el-button type="danger" size="small" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- <el-button type="primary" @click="go">跳转播放页</el-button> -->
    </div>
  </div>
  <h3 v-else>请在地址栏带上userid和secretkey和writeToken 相关参数</h3>
</template>

<script setup>
  import { onMounted, onUnmounted, getCurrentInstance, ref,reactive,toRefs, inject } from 'vue';
  import PlvVideoUpload from "@polyv/vod-upload-js-sdk/vod-upload-js-sdk.min.js";
  import md5 from 'js-md5'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useMainStore } from '@/store/config'
  import { useRouter } from "vue-router";
  const router = useRouter()
  const isChange = ref(false) // 上传文件input
  /**const go = () => {
    router.push('/test')
}**/

  const $store = useMainStore();
  if(!$store.userid || !$store.secretkey || !$store.writeToken) {
    isChange.value = false;
    ElMessageBox.alert('请在地址栏带上userid和secretkey和writeToken 相关参数', '提示', {
      type: 'error',
      confirmButtonText: 'OK',
      callback: (action) => {
      },
    })
  }else {
    isChange.value = true;
  }
  const utils = inject('$utils');
  const inputer = ref(null) // 上传文件input
  const tableData = ref([]) // 表格数据
  const videoUpload = ref(null) // 视频上传实例
  const ptime = ref(null) // 当前时间戳

  videoUpload.value = new PlvVideoUpload({
    region: 'line1', // (可选)上传线路, 默认line1
    events: {
      Error: (err) => { // 错误事件回调
        console.log(err);
        let errMag = `（错误代码：${err.code}）${err.message}`;
        ElMessageBox.alert(errMag, '提示', {
          type: 'error',
          confirmButtonText: 'OK',
          callback: (action) => {
          },
        })
      },
      UploadComplete: (data) => { // 全部上传任务完成回调
        console.info('上传结束：', data);
        ElMessage({
          message: '全部上传任务完成',
          type: 'success',
        })
      }
    }
  });

  const transformSize = (bytes) => {// 文件大小转换
      const bt = parseInt(bytes);
      let result;
      if (bt === 0) {
        result = '0B';
      } else {
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(bt) / Math.log(k));
        if (typeof i !== 'number') {
          result = '-';
        } else {
          result = (bt / Math.pow(k, i)).toFixed(2) + sizes[i];
        }
      }
      return result;
  }

  const addTableData = (data) => { // 增加表格数据
    let obj = {
      id: data.id,
      fileName: data.fileData.title,
      size: data.fileData.size,
      progress: 0
    }
    tableData.value.push(obj)
  }

  const doUpload = () => {// 选择文件
    console.log(inputer.value.files)
    const files = Array.from(inputer.value.files) // 类数组转为数组
    if (files.length > 0) {
      files.forEach((file, index, arr) => {
        let fileSetting = { // 文件上传相关信息设置
          title: file.name, // 标题
          desc: 'jssdk上传', // 描述
          cataid: '', // 上传分类目录ID
          tag: '', // 标签
          luping: 0, // 是否开启视频课件优化处理，对于上传录屏类视频清晰度有所优化：0为不开启，1为开启
          keepsource: 0, // 是否源文件播放（不对视频进行编码）：0为编码，1为不编码
          state: '' //用户自定义信息，如果提交了该字段，会在服务端上传完成回调时透传返回。
        }
        let uploadManager = videoUpload.value.addFile(
          file, // file 为待上传的文件对象
          {
            FileStarted: onFileStarted,// 文件开始上传回调
            FileProgress: onFileProgress,// 文件上传中回调
            FileSucceed: onFileSucceed,// 文件上传成功回调
            FileFailed: onFileFailed,// 文件上传失败回调
            FileStopped: onFileStopped,// 文件上传停止回调
          },
          fileSetting
        );

        addTableData(uploadManager)
      })
    }
  }

  const start = (uploaderid) => {// 单个上传
    console.log(uploaderid)
    videoUpload.value.resumeFile(uploaderid);
  }

  const stop = (uploaderid) => {// 单个暂停
    console.log(uploaderid)
    videoUpload.value.stopFile(uploaderid);
  }

  const remove = (row)=> {// 单个删除
    videoUpload.value.removeFile(row.id);
    tableData.value = tableData.value.filter((item) => item.id !== row.id)
    inputer.value.value = ''
  }

  const startAll = () => {// 全部上传
    if (videoUpload.value) {
      videoUpload.value.startAll();
    }
  }

  const pauseAll = () => {// 全部暂停
    if (videoUpload.value) {
      videoUpload.value.stopAll();
    }
  }

  const clearAll = () => {// 全部删除
    if (videoUpload.value) {
      videoUpload.value.clearAll();
      tableData.value = []
      inputer.value.value = ''
    }
  }

  const onFileStarted = (data) => {
    console.log("文件上传开始: ", data);
    tableData.value.filter((item) => item.id === data.uploaderid)[0].progress = 0
  }

  const onFileProgress = (data) => {
    let p = parseInt(data.progress * 100);// 上传的进度条
    console.log("文件上传中: ", data);
    tableData.value.filter((item) => item.id === data.uploaderid)[0].progress = p
  }

  const onFileSucceed = (data) => {
    console.log("文件上传成功: ", data.fileData.vid);
  }
  const onFileFailed = (data) => {
    console.log("文件上传失败: ", data);
    // 失败之后将对应的数据删除
    ElMessageBox.alert(data.errData, '提示', {
      type: 'error',
      confirmButtonText: 'OK',
      callback: (action) => {
        videoUpload.value.removeFile(data.uploaderid);
        tableData.value = tableData.value.filter((item) => item.id !== data.uploaderid)
        inputer.value.value = ''
      },
    })
  }
  const onFileStopped = (data) => {
    console.log("文件上传停止: ", data);
  }

  const getSignData =() =>{ // 加密信息参数
    let hash = md5(ptime.value + $store.writeToken)
    let sign = md5($store.secretkey + ptime.value)
    return {
      hash: hash,
      sign: sign,
    }
  }

  const getUserData =() => { // 获取用户详细信息
    ptime.value = new Date().getTime()
    let userData = {
      userid: $store.userid,
      ptime: ptime.value,
      sign: getSignData().sign,
      hash: getSignData().hash
    };
    videoUpload.value.updateUserData(userData);
  }

  const autoUpdateUserData = (timer, videoUpload) => { // 启动获取用户信息
    getUserData(videoUpload);
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(() => {
      autoUpdateUserData(timer, videoUpload);
    }, 3 * 50 * 1000);
  }



  onMounted(async () => {

    autoUpdateUserData(null, videoUpload.value);
  })

</script>

<style scoped>
#default-btn::file-selector-button{
    padding: 6px 10px;
    background-color: #1E9FFF;
    border: 1px solid #1E9FFF;
    border-radius: 3px;
    cursor: pointer;
    color: #fff;
    font-size: 12px;
}
#default-btn{
    font-size: 0;
    margin-right: 20px;
}
.upload-menu {
  margin-bottom: 10px;
}
</style>
